package com.example.im.ui.activity

import android.content.Intent
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.R
import com.example.im.bean.ChatRecord
import com.example.im.bean.UserRoom
import com.example.im.common.Constants
import com.example.im.db.DatabaseStorage
import com.example.im.mvp.presenter.SearchPresenter
import com.example.im.mvp.view.ISearchView
import com.example.im.ui.abstracts.AbstractBaseActivity
import com.example.im.ui.adapter.SearchFriendAdapter
import com.example.im.ui.adapter.SearchRoomAdapter
import kotlinx.android.synthetic.main.activity_search.*

class SearchActivity : AbstractBaseActivity<SearchPresenter>(), ISearchView,
    SearchFriendAdapter.OnClickItemListener,
    SearchRoomAdapter.OnClickItemListener {

    private val friends = mutableListOf<UserRoom>()
    private val rooms = mutableListOf<UserRoom>()
    private var friendAdapter: SearchFriendAdapter? = null
    private var roomAdapter: SearchRoomAdapter? = null

    private var flag = -1

    override val layoutId: Int
        get() = R.layout.activity_search

    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        friendAdapter = SearchFriendAdapter(this, friends)
        friendAdapter!!.setOnItemClickListener(this)
        recycler_view_friend.layoutManager = LinearLayoutManager(this)
        recycler_view_friend.adapter = friendAdapter

        roomAdapter = SearchRoomAdapter(this, rooms)
        roomAdapter!!.setOnItemClickListener(this)
        recycler_view_group.layoutManager = LinearLayoutManager(this)
        recycler_view_group.adapter = roomAdapter

        edit_search.requestFocus()

        frame_clear.setOnClickListener {
            edit_search.text.clear()
        }

        val content = intent.getSerializableExtra(Constants.BUNDLE_T0_SEARCH_DATA)
        flag = if (content != null) {
            val friends = DatabaseStorage.getUserRoomStorageByType(Constants.CHAT_KIND_1) ?: return
            this.onSearchFriendGood(friends)
            val rooms = DatabaseStorage.getUserRoomStorageByType(Constants.CHAT_KIND_2) ?: return
            this.onSearchGroupRoom(rooms)
            1
        } else 0
    }

    override fun initPresenter() {
        mPresenter = SearchPresenter(this, this)
        mPresenter!!.searchVague(edit_search)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onSearchFriendGood(friends: MutableList<UserRoom>) {
        if (friends.isEmpty()) {
            linear_search_friend.visibility = View.GONE
        } else if (linear_search_friend.visibility == View.GONE) {
            linear_search_friend.visibility = View.VISIBLE
        }
        friendAdapter!!.setKeyword(edit_search.text.toString())
        friendAdapter!!.addData(friends)
    }

    override fun onSearchGroupRoom(rooms: MutableList<UserRoom>) {
        if (rooms.isEmpty()) {
            linear_search_group.visibility = View.GONE
        } else if (linear_search_group.visibility == View.GONE) {
            linear_search_group.visibility = View.VISIBLE
        }
        roomAdapter!!.setKeyword(edit_search.text.toString())
        roomAdapter!!.addData(rooms)
    }

    override fun onClickItemFriend(view: View, position: Int) {
        if (flag == 0) {
            val intent = Intent(this, UserActivity::class.java)
            intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_POINT, Constants.BUNDLE_T0_USER_POINT_1)
            intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_DATA, friends[position])
            startActivity(intent)
            finish()
        }
        if (flag == 1) {
            relayDialog(friends[position])
        }
    }

    override fun onClickItemRoom(view: View, position: Int) {
        if (flag == 0) {
            val intent = Intent(this, RoomActivity::class.java)
            intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_POINT, Constants.BUNDLE_T0_ROOM_POINT_1)
            intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_DATA, rooms[position])
            startActivity(intent)
            finish()
        }
        if (flag == 1) {
            relayDialog(rooms[position])
        }
    }

    private fun relayDialog(userRoom: UserRoom) {

        var chatRecord = intent.getSerializableExtra(Constants.BUNDLE_T0_SEARCH_DATA)
            ?: return
        chatRecord = chatRecord as ChatRecord

        val contentText = if (chatRecord.type != Constants.CHAT_TYPE_TEXT) {
            chatRecord.body + chatRecord.file!!.name
        } else chatRecord.body

        val dialog = AlertDialog.Builder(this)
        dialog.setTitle("转发给：${userRoom.nickname}")
        dialog.setMessage("\n内容：${contentText}")
        dialog.setPositiveButton("确定") { d, _ ->
            d.dismiss()
            val intent = Intent(this, ChatActivity::class.java)
            intent.putExtra("FRIEND_OR_ROOM", userRoom)
            intent.putExtra("CHAT_CONTENT", chatRecord)
            setResult(RESULT_OK, intent)
            finish()
        }
        dialog.setNegativeButton("取消", null)
        dialog.show()
    }
}